package com.example.coffeejava.Config;

import cn.hutool.core.bean.BeanUtil;
import com.example.coffeejava.Dto.UserDto;
import com.example.coffeejava.Entity.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.example.coffeejava.utils.Constants.LOGIN_USER_KEY;

public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,Object handler){
        System.out.println(UserHolder.getUser()+"123");
        //如果user是空，返回401
        String token=httpServletRequest.getHeader("authorization");
        String key=LOGIN_USER_KEY+token;
        //获取缓存里面usermap
        Map<Object,Object> usermap=stringRedisTemplate.opsForHash().entries(key);
        //hashmap转换为userDto
        UserDto userDto= BeanUtil.fillBeanWithMap(usermap,new UserDto(),false);
        System.out.println(userDto+"userDto");
        if(userDto==null){
            httpServletResponse.setStatus(401);
            return false;
        }
        return true;
    }
}
